<script setup lang="tsx">
import { reactive, ref, unref, computed } from 'vue'
import { ElLink, ElSpace, ElMessageBox, ElMessage } from 'element-plus'
import { Table, TableColumn } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { formatToDateTime } from '@/utils/dateUtil'
import AutoComplete from '@/components/AutoComplete/src/AutoComplete.vue'
import taskNewVue from './taskNew.vue'
import { deleteTaskApi, findTaskPageApi } from '@/api/task'
import { taskType } from '@/api/task/types'
import { SUCCESS_CODE } from '@/constants'

defineOptions({
  name: 'TaskManage'
})

const emit = defineEmits(['changeComponent'])

const searchParams = ref({})
const taskAddVisible = ref(false)
const buttonType = ref('')
const updTaskUuid = ref('')
const selectedRows = ref<any[]>([])

const getColumns = () => {
  const columns = [
    /*{
      field: 'selection',
      type: 'selection'
    },*/
    {
      field: 'name',
      label: '任务名称'
    },
    {
      field: 'status',
      label: '状态',
      slots: {
        default: (data: any) => {
          const row = data.row
          return <>{row.status === '1' ? '已完成' : '未完成'}</>
        }
      }
    },
    {
      field: 'remark',
      label: '描述'
    },
    {
      field: '',
      label: '截止时间',
      width: 200,
      slots: {
        default: (data: any) => {
          const row = data.row
          return <>{formatToDateTime(row.end_time)}</>
        }
      }
    },
    {
      field: 'action',
      label: '操作',
      fixed: 'right',
      width: 100,
      slots: {
        default: (data) => {
          const row = data.row
          return (
            <>
              <ElSpace>
                <ElLink
                  type="primary"
                  underline={false}
                  disabled={row.status === '1'}
                  onClick={() => handleUpdate(row)}
                >
                  编辑
                </ElLink>

                <ElLink type="primary" underline={false} onClick={() => handleRemove(row)}>
                  删除
                </ElLink>
              </ElSpace>
            </>
          )
        }
      }
    }
  ]
  return columns
}
const columns = reactive<TableColumn[]>(getColumns() as TableColumn[])
buttonType.value = 'add'
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const params = {
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    }
    if (queryConditions.value.length) {
      queryConditions.value.forEach((item) => {
        console.log(item)
        params[item.value] = item.name
      })
    }
    if (params.name == null) {
      params.name = ''
    }
    if (params.status == null) {
      params.status = ''
    }
    const res = await findTaskPageApi(params)
    return {
      list: res.retObj.data,
      total: res.retObj.total
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, refresh } = tableMethods

const handleSelectionChange = (val) => {
  selectedRows.value = val
}
const queryConditions = ref<{ [key in string]: any }[]>([])

const searchItem = computed(() => {
  const searchArr = [
    { name: '任务名称', id: 'name' },
    {
      name: '状态',
      id: 'status',
      type: 'list',
      options: [
        { name: '已完成', key: '1' },
        { name: '未完成', key: '0' }
      ]
    }
  ]
  return searchArr
})

const handelSelect = (value) => {
  queryConditions.value = value
  getList()
}
const handleUpdate = (row) => {
  selecedRow.value = row
  buttonType.value = 'edit'
  updTaskUuid.value = row.uuid
  taskAddVisible.value = true
}
const handleRemove = async (row) => {
  let title = ''
  if (row) {
    title = '您确定要删除任务 <b>' + row.name + '</b> 吗？'
  }
  ElMessageBox.confirm(title, '删除任务', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    dangerouslyUseHTMLString: true,
    type: 'warning'
  })
    .then(async () => {
      const params = {
        uuid: row.uuid
      }
      const response = await deleteTaskApi(params)
        .catch(() => {})
        .finally(() => {})
      if (response.code === SUCCESS_CODE) {
        ElMessage.success('删除成功！')
        refresh()
      }
    })
    .catch(() => {})
}
function headerCellStyle() {
  return { background: '#f5f5f5' }
}
const selecedRow = ref<taskType>({
  uuid: '',
  name: '',
  state: '',
  end_time: '',
  remark: '',
  user_id: ''
})
function handleAdd() {
  taskAddVisible.value = true
}
</script>

<template>
  <div>
    <div class="el-card-t mb-3">
      <AutoComplete :data-list="searchItem" @select="handelSelect" />
    </div>
    <Table
      class="table-contain"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :header-cell-style="headerCellStyle"
      :columns="columns"
      :data="dataList"
      row-key="uuid"
      :loading="loading"
      sortable
      :show-action="true"
      :pagination="{
        total: total
      }"
      @selection-change="handleSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
    >
      <template #customToolButtons>
        <BaseButton type="primary" @click="handleAdd">添加</BaseButton>
        <!--        <BaseButton type="primary" :disabled="isShowBtn" @click="handleUpdate(selectedRows[0])">
          编辑
        </BaseButton>
        <BaseButton type="primary" :disabled="selectedRows.length == 0" @click="handleRemove">
          删除
        </BaseButton>-->
      </template>
    </Table>
  </div>
  <taskNewVue
    v-model="taskAddVisible"
    v-if="taskAddVisible"
    :type="buttonType"
    :task-uuid="updTaskUuid"
    @handle-task="refresh"
  />
</template>

<style scoped lang="less"></style>
